import VueCookies from 'vue-cookies'
import http from '@/utils/request'

export default {
  namespaced: true,
  state: {
    accessToken: VueCookies.get('accessToken'),
    refreshToken: VueCookies.get('refreshToken'),
    userInfo: VueCookies.get('userInfo')
  },
  mutations: {
    SET_ACCESS_TOKEN: (state, token) => {
      VueCookies.set('accessToken', token)
      state.accessToken = token
    },
    CLEAN_ACCESS_TOKEN: (state) => {
      VueCookies.remove('accessToken')
      state.accessToken = null
    },
    SET_REFRESH_TOKEN: (state, token) => {
      VueCookies.set('refreshToken', token)
      state.refreshToken = token
    },
    CLEAN_REFRESH_TOKEN: (state) => {
      VueCookies.remove('refreshToken')
      state.refreshToken = null
    },
    SET_USER_INFO: (state, userinfo) => {
      VueCookies.set('userInfo', userinfo)
      state.userInfo = userinfo
    },
    CLEAN_USER_INFO: (state) => {
      VueCookies.remove('userInfo')
      state.userInfo = null
    }
  },
  actions: {
    set_LoginInfo ({commit}, data) {
      commit('SET_ACCESS_TOKEN', data['access_token'])
      commit('SET_REFRESH_TOKEN', data['refresh_token'])
      commit('SET_USER_INFO', data['userInfo'])
    },
    set_userInfo ({commit}, data) {
      const newInfo = {
        alias: data,
        avatar: ''
      }
      commit('SET_USER_INFO', newInfo)
    },
    clean_LoginInfo ({commit}) {
      commit('CLEAN_ACCESS_TOKEN')
      commit('CLEAN_REFRESH_TOKEN')
      commit('CLEAN_USER_INFO')
    },
    refresh_token ({commit}) {
      return new Promise((resolve, reject) => {
        http.get(http.adornUrl('/login/refresh')).then(response => {
          const result = response.data
          if (result.code === 200) {
            const accessToken = result.data.accessToken
            const refreshToken = result.data.refreshToken
            commit('SET_ACCESS_TOKEN', accessToken)
            commit('SET_REFRESH_TOKEN', refreshToken)
            resolve(result)
          } else {
            reject(result)
          }
        }).catch(error => {
          reject(error.msg)
        })
      })
    }
  }
}
